<?php
// 接口-采购统计
namespace interface\v1;

use verify;

class purchaseStatisticsClass extends index
{
	private const page    = 'purchaseApply';
	private const table   = 'purchase_order';
	private const tableMx = 'purchase_order_detail';
	private const title   = '采购订单';
	
	function index()
	{
		$this->code = 1;
		$months     = self::dateRange(date('Y-m-d', strtotime('-1 year')), date('Y-m-d'));
		$res        = [];
		foreach ($months as $m) {
			$twhere        = self::timeComparison($m, 'month', 'targetDate');
			$rwhere        = self::timeComparison($m, 'month', 'b.recordDate');
			$amountPayable = find([
				'table'  => "record",
				'field'  => "IFNULL(sum(abs(money)),0) as money",
				'single' => " coid = '" . self::$coid . "' and classify = '采购收货' " . $twhere,
			])['num'] ?? 0;
			$paymentAmount = (float)find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => " coid = '" . self::$coid . "' and b.state = '已确认' and b.classify = 0 " . $rwhere, 'sum' => "money"));
			//核销单
			$paymentAmount += (float)find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => " coid = '" . self::$coid . "' and b.state = '已确认'  and b.type = '预付冲应付' " . $rwhere, 'sum' => "money"));
			$res[]         = [
				'amountPayable' => round($amountPayable / 10000, 2),
				'paymentAmount' => round($paymentAmount / 10000, 2),
			];
		}
		
		$this->resp['data'] = [
			'title'     => ['应付金额', '付款金额'],
			'dateRange' => $months[0] . '~' . end($months),
			"data"      => $months,
			"series"    => [
				[
					'name'   => '应付金额',
					"type"   => 'line',
					"smooth" => 1,
					'data'   => array_column($res, 'amountPayable'),
				],
				[
					'name'   => '付款金额',
					"type"   => 'line',
					"smooth" => 1,
					'data'   => array_column($res, 'paymentAmount'),
				],
			],
		];
	}
	
	/**
	 * 按期交货率
	 *
	 * @return void
	 */
	function deliveryRate()
	{
		$this->code = 1;
		$months     = self::dateRange(date('Y-m-d', strtotime('-1 year')), date('Y-m-d'));
		$res        = [];
		foreach ($months as $m) {
			$res[] = [
				'onScheduleNum' => inventoryDefaultClass::deliveryRate('按期交货订单笔数', $m),
				'delayNum'      => inventoryDefaultClass::deliveryRate('延期交货订单笔数', $m),
			];
		}
		$this->resp['data'] = [
			'title'     => ['按期交货订单笔数', '延期交货订单笔数'],
			'dateRange' => $months[0] . '~' . end($months),
			"data"      => $months,
			"series"    => [
				[
					'name'   => '按期交货订单笔数',
					"type"   => 'bar',
					"smooth" => 1,
					'data'   => array_column($res, 'onScheduleNum'),
				],
				[
					'name'   => '延期交货订单笔数',
					"type"   => 'bar',
					"smooth" => 1,
					'data'   => array_column($res, 'delayNum'),
				],
			],
		];
	}
	
	public function dataBoard()
	{
		/**
		 * 金额单位格式化
		 *
		 * @param $money
		 * @return string
		 */
		function moneyUnit($money): string
		{
			return $money > 10000 ? round(($money / 10000), 2) . '万' : round($money, 2);
		}
		
		$this->code = 1;
		$date       = $this->post('date');
		//采购金额
		$where = " and coid = '" . self::$coid . "' ";
		if ($date) {
			$where .= $this->timeComparison($date, 'date', 'recordDate');
		}
		$purchaseMoney = find(array('table' => 'purchase_order', 'where' => "state = '已确认'" . $where, 'sum' => "money"));
		
		//付款金额
		if ($date) {
			$where .= $this->timeComparison($date, 'date', 'b.recordDate');
		}
		$paymentAmount = (float)find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => " coid = '" . self::$coid . "' and b.state = '已确认' and b.classify = 0  " . $where, 'sum' => "money"));
		//核销单
		$paymentAmount += (float)find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => " coid = '" . self::$coid . "' and b.state = '已确认' and b.type = '预付冲应付' " . $where, 'sum' => "money"));
		$where         = '';
		//来料质检合格率
		$qRate = static::qualityOrderRate($date);
		//按期交货率
		$where                = ''; //recordDate
		$orderNum             = find([
			'table'  => "purchase_order",
			'field'  => "IFNULL(count(id),0) as num",
			'single' => " coid = '" . self::$coid . "' state = '已确认' " . $where,
		])['num'] ?? 0;
		$onScheduleNum        = find([
			'table'  => "purchase_order",
			'field'  => "IFNULL(count(id),0) as num",
			'single' => " coid = '" . self::$coid . "' and state = '已确认' and actual_delivery_date is not null and deliveryDate >= actual_delivery_date " . $where,
		])['num'] ?? 0;
		$scheduleDeliveryRate = ($orderNum > 0 ? round(($onScheduleNum / $orderNum) * 100, 1) : 0);
		
		$this->resp['data'] = [
			[
				'type'  => '采购金额',
				'money' => moneyUnit($purchaseMoney),
			],
			[
				'type'  => '付款金额',
				'money' => moneyUnit($paymentAmount),
			],
			[
				'type'  => '供应商安全交货率',
				'money' => $scheduleDeliveryRate > 0 ? $scheduleDeliveryRate . '%' : $scheduleDeliveryRate,
			],
			[
				'type'  => '来料质检合格率',
				'money' => $qRate > 0 ? $qRate . '%' : $qRate,
			],
		];
	}
	
	/**
	 * 来料质检
	 *
	 * @param $date
	 * @return string|int
	 */
	public static function qualityOrderRate($date = '', $type = 'date')
	{
		$where = '';
		if ($date) {
			$where .= self::timeComparison($date, $type, 'checkTime');
		}
		$qualityOrder = find([
			'table'  => "quality_order",
			'field'  => "IFNULL(sum(num),0) as num,IFNULL(sum(passNum),0) as passNum",
			'single' => " coid = '" . self::$coid . "' and state = '已质检' and type = 1 " . $where,
		]);
		return ((float)$qualityOrder['num'] > 0 ? round(((float)$qualityOrder['passNum'] / (float)$qualityOrder['num']) * 100, 1) : 0);
	}
	
	/**
	 * 来料质检合格率
	 *
	 * @return void
	 */
	function qualityRate()
	{
		$this->code = 1;
		$months = self::dateRange(date('Y-m-d', strtotime('-1 year')), date('Y-m-d'));
		$res    = [];
		foreach ($months as $month) {
			$res[] = static::qualityOrderRate($month, 'month');
		}
		$this->resp['data'] = [
			'title'     => ['合格率'],
			'dateRange' => $months[0] . '~' . end($months),
			"data"      => $months,
			"series"    => [
				[
					'name'   => '合格率',
					"type"   => 'line',
					"smooth" => 1,
					'data'   => $res,
				],
			],
		];
	}
	
	/**
	 * 供应商
	 *
	 * @return void
	 */
	function supplier()
	{
		$where              = $this->post('date') ? self::timeComparison($this->post('date'), 'date', 'p.recordDate') : '';
		$sql                = " SELECT (@i:=@i+1) as no, s.name, any_value(IFNULL(SUM(money), 0)) as total FROM `purchase_order` as p,supplier as s,(SELECT @i:=0) as i WHERE p.supplierId = s.id AND p.state = '已确认' AND p.coid = '" . self::$coid . "' {$where} GROUP BY supplierId ORDER BY total DESC; ";
		$resp               = self::sqlFind($sql);
		$this->code         = 1;
		$this->resp['data'] = $resp;
	}
	
	/**
	 * 物料
	 *
	 * @return void
	 */
	function material()
	{
		$where = $this->post('date') ? self::timeComparison($this->post('date'), 'date', 'p.recordDate') : '';
		$sql   = "SELECT  m.name, any_value(IFNULL(sum(d.money*(1+d.rate)), 0)) as total FROM `purchase_order` as p, `purchase_order_detail` as d, `material` as m,(SELECT @i:=0) as i WHERE d.materialId = m.id AND p.id = d.orderId AND p.state = '已确认' AND p.coid = '" . self::$coid . "' $where GROUP BY materialId ORDER BY total DESC;";
		$resp  = self::sqlFind($sql);
		$res   = [];
		foreach ($resp as $key => $item) {
			$item['no'] = $key + 1;
			$res[]      = $item;
		}
		$this->code         = 1;
		$this->resp['data'] = $res;
	}
	
	
	function orderToId()
	{
		$orderNo = $this->post('orderNo');
		if (self::isNull($orderNo)) {
			$this->resp['warn'] = '采购单号不能为空';
		} else {
			$info = query(self::table, " orderNo = '$orderNo'  ");
			if (empty($info['id'])) {
				$this->resp['warn'] = '未找到此单号的采购单号';
			} else {
				$this->code         = 1;
				$this->resp['data'] = $info['id'];
			}
		}
	}
}



